<template>
    <div ref="box"></div>
  </template>
  
  <script>     
  var { render } = require("amis");
  import ReactDOM from "react-dom";

  export default {
    props: {
      amisjson: {
        type: Object,
        required: false,
      },
      dataSource: {
        type: Object,
        required: false,
      },
      disabled: {
        type: Boolean,
        required: false,
      },
      asForm: {
        //是否作为表单使用，是的话会隐藏提交按钮，没按钮或者没Form会添加
        type: Boolean,
        required: false,
      },
      autoAddReason: {
        type: Boolean,
        required: false,
      },
      keyName: {
        type: String,
        require: false
      },
      fetchInitData: {
        type: Boolean,
        default: true,
        required: false,
      }
    },
    watch: {
      amisjson: function (data) {
        console.log('amisjsons', this.amisjson)
        this.init()
      },
    },
    mounted() {
      
        this.initData = {};
        this.init();
     
      window.addEventListener('message', this.onMessage)
    },
    beforeDestroy() {
      window.removeEventListener('message', this.onMessage)
    },
    data() {
      return {
        hasForm: false,
        guid: null,
        initData: null
      }
    },
    methods: {
      init() {
        if (this.initData == null) {
          //等待加载完成
          setTimeout(this.init, 200)
          return
        }
        if (this.amisjson == null) return;
        this.guid = this.getGuid();
        var dataSource
        if (this.dataSource) {
          dataSource = this.dataSource
        } else dataSource = {}
        // //字典附加内容
        // var dicAttachData = getDictDatas(DICT_TYPE.AMIS_INIT_DATA_ATTACH)
        // for (var i in dicAttachData) {
        //   var item = dicAttachData[i]
        //   dataSource[item.label] = item.value
        // }
        dataSource = Object.assign(dataSource, this.initData);
       
        if (this.amisjson.data == null) this.amisjson.data = dataSource
        else this.amisjson.data = Object.assign(this.amisjson.data, dataSource)
        this.replaceAmisHref(this.amisjson)
        if (this.asForm && !this.hasForm) {
          var form = {
            type: 'form',
            body: this.amisjson.body,
            wrapWithPanel: false,
            mode: 'horizontal',
          }
          this.amisjson.body = form
          this.rewriteForm(form)
        }
  
        // let amisScoped = amis.embed(divBox, this.amisjson);
        /* @require index.tsx 标记为同步依赖，提前加载 */
        // amis.embed(divBox, this.amisjson);
        this.amisLoad()
      },
  
      amisLoad: function () {
        
        var divBox = this.$refs['box']
        var amisUrl = ""
        var baseUrl = ""
        var env = {
          //amis 环境重写
          fetcher: (option) => {
            //   {
            //   url, // 接口地址
            //   method, // 请求方法 get、post、put、delete
            //   data, // 请求数据
            //   responseType,
            //   config, // 其他配置
            //   headers, // 请求头
            // }
           
          },
          notify: (type, msg) => {
            //: 'error' | 'success' /**/,      msg: string /*提示内容*/
            if (type == 'error') this.$message.error(msg)
            else this.$message.success(msg)
          },
          jumpTo: (location, action) => {
            // location: string /*目标地址*/,
            //   action: any /* action对象*/
            //   // 用来实现页面跳转, actionType:link、url 都会进来。
            if (action.blank) {
              //新窗口打开
              window.open(location)
              return
            }
            //tab打开
            location = location.replace(window.location.origin, '')
            console.log('jumpTo:' + location)
            var queryPos = location.indexOf('?')
            var query = {}
            if (queryPos > 0) {
              var temp = location.substring(queryPos + 1)
              var arr = temp.split('&')
              for (var i in arr) {
                var tempArr = arr[i].split('=')
                query[tempArr[0]] = tempArr[1]
              }
            } else query = null
            this.$router.push(location, query)
          },
          //     updateLocation:()=>{
          //           //   location: string /*目标地址*/,
          // //   replace: boolean /*是replace，还是push？*/
          // // 地址替换，跟 jumpTo 类似
          //     }
        }
        // amis.require(['82e9d55'], (app) => {
        //   app.loadSchema(divBox, this.amisjson, env)
        // })
        ReactDOM.render(render(this.amisjson, {theme:null}, env), divBox);
      },
      replaceAmisHref: function (obj) {
        for (var i in obj) {
          var item = obj[i]
          if (!item) continue
          // if (item.type == "button" && item.actionType == "link" && item.link) {
          //   item.actionType = null;
          //   item.onClick =
          //     "console.log(props.data,'点击'),window.postMessage({name:'amis-location-href',data:{label:'" +
          //     item.label +
          //     "',link:'" +
          //     item.link +
          //     "', data:props.data}},'*');";
          //   console.log(item, "替换跳转");
          //   // item.onEvent = {
          //   //   click: {
          //   //     actions: [
          //   //       {
          //   //         actionType: "custom",
          //   //         script:
          //   //           "window.postMessage({name:'amis-location-href',data:{label:'"+ item.label +"',link:'" +
          //   //           item.link +
          //   //           "', data:event.data}},'*');",
          //   //       },
          //   //     ],
          //   //   },
          //   // };
          // } else
  
          if (typeof item == 'object') {
            if (item.type == 'form') {
              this.rewriteForm(item)
            }
            this.replaceAmisHref(item)
          }
        }
      },
      rewriteForm(form) {
        if (process.env.ENV != "development") form.debug = false;
        this.hasForm = true
        var hideBtn = this.asForm
        if (this.disabled) {
          form.disabled = true
          hideBtn = true
        }
        if (!this.asForm) return
        if (form.actions == null) form.actions = []
        var submitBtn = form.actions.find((item) => item.type == 'submit')
        form.wrapWithPanel = false
        console.log('重写form event为postmessage')
        var submitActions = [];
        if (form.onEvent != null && form.onEvent.submitSucc != null && form.onEvent.submitSucc.actions != null) {
          //表单定义的事件
          submitActions.push(form.onEvent.submitSucc.actions);
  
        }
        //加上提交的事件
        submitActions.push(
          {
            "actionType": "broadcast",
            "args": {
              "eventName": "form-submit"
            },
            "data": "${event.data}"
          },
          {
            actionType: 'custom',
            script:
              "window.postMessage({name:'amis-submit-form',data:{guid:'" + this.guid + "',data:event.data}},'*');console.log(event.data,'发送amis-submit-form');",
          })
        form.onEvent = {
          submitSucc: {
            actions: submitActions
          },
          submitFail: {
            actions: [
              {
                actionType: 'toast',
                args: {
                  msgType: 'info',
                  msg: '提交失败',
                },
              },
            ],
          },
        }
        if (hideBtn) {
          this.amisjson.css = {
            '.myClass': {
              display: 'none',
            },
          }
          // submitBtn.className= "myClass";
          // form.wrapWithPanel= false;
        }
        if (submitBtn == null) {
          submitBtn = {
            type: 'submit',
            label: '提交',
            className: 'myClass',
          }
          form.body.push(submitBtn)
        }
        // setTimeout(() => {
        //   var footerWrap =divBox.getElementsByClassName("cxd-Panel-footerWrap");
        //     if(footerWrap && footerWrap.length >0 ){
        //       footerWrap[0].style.display="none";
        //     }
  
        // }, 500);
  
        if (this.autoAddReason) {
          form.body.push({
            type: 'textarea',
            label: '备  注',
            name: 'reason',
            // required: true,
          })
        }
      },
      onMessage(e) {
        if (e.data.name == 'amis-submit-form' && e.data.data.guid == this.guid) {
          //提交流程表单，开始流程
          this.$emit('submit', { keyName: this.keyName, data: e.data.data.data });
        }
      },
      getGuid() {
        return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16);
        });
      },
      submitForm() {
        var divBox = this.$refs['box']
        var btns = divBox.getElementsByTagName('button')
        if (btns == null || btns.length == 0)
          btns = divBox.getElementsByTagName('input')
        if (btns && btns.length > 0) {
          forEach(btns, (x) => {
            if (x.type == 'submit') {
              x.click()
            }
          })
        } else {
          console.log('amis内需要有submit按钮')
        }
      },
    },
  }
  </script>
  